package com.shensi.adminCollect.service.customer.impl;

import com.shensi.adminCollect.common.enums.DecimalConstant;
import com.shensi.adminCollect.domain.customer.CustomerCardSetting;
import com.shensi.adminCollect.domain.customer.CustomerCardSettingDetail;
import com.shensi.adminCollect.domain.customer.CustomerCardSettingDetailContent;
import com.shensi.adminCollect.mapper.customer.CustomerCardSettingDetailContentMapper;
import com.shensi.adminCollect.mapper.customer.CustomerCardSettingDetailMapper;
import com.shensi.adminCollect.mapper.customer.CustomerCardSettingMapper;
import com.shensi.adminCollect.service.customer.ICustomerCardSettingDetailService;
import com.shensi.adminCollect.vo.customer.CalPresentAmt;
import com.shensi.common.core.domain.model.LoginUser;
import com.shensi.common.core.utils.SecurityUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 客户电子会员卡充值优惠设置明细Service业务层处理
 *
 * @author qujia
 * @date 2021-04-06
 */


@Service
public class CustomerCardSettingDetailServiceImpl implements ICustomerCardSettingDetailService
{
    private static Logger logger =(Logger) LoggerFactory.getLogger(CustomerCardSettingDetailServiceImpl.class);
    @Resource
    private CustomerCardSettingDetailMapper customerCardSettingDetailMapper;
    @Resource
    private CustomerCardSettingMapper customerCardSettingMapper;

    @Resource
    private CustomerCardSettingDetailContentMapper customerCardSettingDetailContentMapper;




    /**
     * 查询客户电子会员卡充值优惠设置明细
     *
     * @param id 客户电子会员卡充值优惠设置明细ID
     * @return 客户电子会员卡充值优惠设置明细
     */
    @Override
    public CustomerCardSettingDetail selectCustomerCardSettingDetailById(Long id)
    {
        return customerCardSettingDetailMapper.selectCustomerCardSettingDetailById(id);
    }

    /**
     * 查询客户电子会员卡充值优惠设置明细列表
     *
     * @param customerCardSettingDetail 客户电子会员卡充值优惠设置明细
     * @return 客户电子会员卡充值优惠设置明细
     */
    @Override
    public List<CustomerCardSettingDetail> selectCustomerCardSettingDetailList(CustomerCardSettingDetail customerCardSettingDetail)
    {
        return customerCardSettingDetailMapper.selectCustomerCardSettingDetailList(customerCardSettingDetail);
    }

    /**
     * 新增客户电子会员卡充值优惠设置明细
     *
     * @param customerCardSettingDetail 客户电子会员卡充值优惠设置明细
     * @return 结果
     */
    @Override
    @Transactional
    public int insertCustomerCardSettingDetail(CustomerCardSettingDetail customerCardSettingDetail)
    {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        customerCardSettingDetail.setCreateTime(new Date());
        customerCardSettingDetail.setCreateUser(currentUser.getUser().getUserId());

        customerCardSettingDetailMapper.insertCustomerCardSettingDetail(customerCardSettingDetail);
        List<CustomerCardSettingDetailContent> contentList = customerCardSettingDetail.getContentList();
        for (CustomerCardSettingDetailContent customerCardSettingDetailContent : contentList) {
            List<String> couponIssueId = customerCardSettingDetailContent.getCouponIssueId();
            if(couponIssueId!=null&&couponIssueId.size()>0){
                List<String> collect = couponIssueId;
                String join = String.join(",", collect);
                customerCardSettingDetailContent.setCouponIssueIds(join);
            }
            customerCardSettingDetailContent.setCcsdId(customerCardSettingDetail.getId());
        }
        return customerCardSettingDetailContentMapper.insertBatch(contentList);
    }

    /**
     * 修改客户电子会员卡充值优惠设置明细
     *
     * @param customerCardSettingDetail 客户电子会员卡充值优惠设置明细
     * @return 结果
     */
    @Override
    public int updateCustomerCardSettingDetail(CustomerCardSettingDetail customerCardSettingDetail)
    {
        return customerCardSettingDetailMapper.updateCustomerCardSettingDetail(customerCardSettingDetail);
    }

    /**
     * 批量删除客户电子会员卡充值优惠设置明细
     *
     * @param ids 需要删除的客户电子会员卡充值优惠设置明细ID
     * @return 结果
     */
    @Override
    public int deleteCustomerCardSettingDetailByIds(Long[] ids)
    {
        return customerCardSettingDetailMapper.deleteCustomerCardSettingDetailByIds(ids);
    }

    /**
     * 删除客户电子会员卡充值优惠设置明细信息
     *
     * @param id 客户电子会员卡充值优惠设置明细ID
     * @return 结果
     */
    @Override
    public int deleteCustomerCardSettingDetailById(Long id)
    {
        return customerCardSettingDetailMapper.deleteCustomerCardSettingDetailById(id);
    }

    @Override
    public List<CustomerCardSettingDetail> listDetailInfo(CustomerCardSetting customerCardSetting) {
        return customerCardSettingDetailMapper.listDetailInfo(customerCardSetting);
    }

    @Override
    @Transactional
    public Integer updateStatus(String status, Long[] ids) {
        Integer i=0;
        for (Long id : ids) {
            CustomerCardSettingDetail settingDetail=new CustomerCardSettingDetail();
            settingDetail.setStatus(status);
            settingDetail.setId(id);
            i=i+customerCardSettingDetailMapper.updateCustomerCardSettingDetail(settingDetail);
            //如果是冻结需要冻结优惠券和金额
            if(status.equals(CustomerCardSettingDetail.SETTING_STATUS_FREEZE)){

            }
        }
        return i;
    }

    @Override
    public CalPresentAmt calPresentAmt( String cardOilsType, BigDecimal amt, Long stationId, Long enterpriseId, String payType,boolean checkVipDay) {
        CalPresentAmt calPresentAmt=new CalPresentAmt();
        BigDecimal presentAmt = BigDecimal.ZERO;
        CustomerCardSetting customerCardSetting=new CustomerCardSetting();
        customerCardSetting.setEnterpriseId(enterpriseId);
        CustomerCardSetting cardSetting = customerCardSettingMapper.selectCustomerCardSetting(customerCardSetting);
        if (cardSetting!=null) {
            CustomerCardSettingDetail form = new CustomerCardSettingDetail();
            //form.setParentId(cardSetting.getId());
            //form.setActivityType(CustomerCardSettingDetail.ACTIVITYTYPE_BALANCE);
            form.setDelFlag("0");
            form.setCardType(cardOilsType);
            form.setEnterpriseId(enterpriseId);
            form.setStationId(stationId);
            form.setStatus("NORMAL");
            form.setActivityMode(CustomerCardSettingDetail.ACTIVITY_MODE_RECHARGE);
            form.setPayType(payType);
            form.setNowDate(new Date());
            form.setWeeklySelection(CustomerCardSettingDetail.dateToWeek(new Date()));
            form.setMonthlySelection(CustomerCardSettingDetail.dateToMonth(new Date()));
            List<CustomerCardSettingDetail> customerCardSettingDetails = customerCardSettingDetailMapper.selectCustomerCardSettingDetailList(form);

            //循环优惠规则明细
            for (CustomerCardSettingDetail cardDetail : customerCardSettingDetails) {
                //判断是否在生效时间内
                if(!checkEffectiveTime(cardDetail)) {
                    continue;
                }
                CustomerCardSettingDetailContent contentQuery=new CustomerCardSettingDetailContent();
                contentQuery.setCcsdId(cardDetail.getId());
                List<CustomerCardSettingDetailContent> contentList=customerCardSettingDetailContentMapper.query(contentQuery);
                boolean isBreak=false;
                for (CustomerCardSettingDetailContent content : contentList) {
                    if (amt.compareTo(content.getRechargeAmtLowerLimit()) >=0 && amt.compareTo(content.getRechargeAmtUpperLimit())<0) {
                        //充值优惠类型
                        calPresentAmt.setCcsdId(cardDetail.getId());
                        if(cardDetail.getActivityType().equals(CustomerCardSettingDetail.ACTIVITYTYPE_BALANCE)){
                            if (cardDetail.getSettingRuleType().equals("1")) { //按充值金额
                                presentAmt = content.getPresentAmount(); //当前赠送金额
                            } else if (cardDetail.getSettingRuleType().equals("2")) {      //按充值金额的比例
                                presentAmt = amt.multiply(content.getPresentAmount().multiply(DecimalConstant.O_01)); //当前赠送金额比例的赠送积分
                            }
                        }
                        isBreak=true;
                        break;
                    }
                }
                if(isBreak){
                    break;
                }
            }
            logger.info("日常活动"+presentAmt.toString());

            if (checkVipDay) {
                if (cardSetting.getDiscountTimeSetting().equals("1")) {
                    String discountTime = cardSetting.getDiscountTime();
                    String[] dctime;     //会员充值活动时间
                    if (StringUtils.isNotBlank(discountTime)) {
                        if (discountTime.contains(",")) {
                            dctime = discountTime.split(",");
                        } else {
                            dctime = new String[1];
                            dctime[0] = discountTime;
                        }
                    }else{
                        logger.error("会员充值活动时间为空,id:{}",cardSetting.getId());
                        calPresentAmt.setPresentAmt(presentAmt);
                        return calPresentAmt;
                    }
                    String currentTime = null;

                    String startTimeStr = cardSetting.getStartTime();
                    String endTimeStr = cardSetting.getEndTime();
                    LocalTime startTime = null;
                    LocalTime endTime = null;


                    if (endTimeStr != null && startTimeStr != null) {
                        startTime = LocalTime.parse(startTimeStr);
                        endTime = LocalTime.parse(endTimeStr);
                    }

                    LocalDateTime now = LocalDateTime.now();
                    LocalTime nowTime = now.toLocalTime();

                    String discountTimeType = cardSetting.getDiscountTimeType();     //获取日期类型
                    switch (discountTimeType) {
                        case "1":   //  1.按周来 数据库存的下标从零开始，星期日是零，星期一是1
                            int week = now.getDayOfWeek().getValue();
                            currentTime = String.valueOf(week == 7 ? 0 : week);
                            break;
                        case "2":   //  2.每月的多少号 数据库存的下标从零开始
                            currentTime = String.valueOf(now.getDayOfMonth()-1); //当前时间
                            break;
                        case "3":   //  3.固定日期
                            currentTime = now.toLocalDate().toString();
                            break;
                    }
                    for (String str : dctime) {
                        if (str.equals(currentTime)) {  //如果当前时间在会员日活动时间内
                            //计算会员日内的总赠送金额
                            if (cardSetting.getPresentScale() != null) {
                                if(timeInScope(nowTime,startTime,endTime)){
                                    presentAmt = presentAmt.add(amt.multiply(new BigDecimal(cardSetting.getPresentScale()).multiply(DecimalConstant.O_01)));
                                }
                            }
                            break;
                        }
                    }
                }
            }
        }
        calPresentAmt.setPresentAmt(presentAmt);
        return calPresentAmt;
    }
    @Override
    public boolean checkEffectiveTime(CustomerCardSettingDetail cardDetail) {
        try{
            Date nowDate = new Date();
            String periodType = cardDetail.getPeriodType();
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyy-MM-dd");
            SimpleDateFormat simpleDateFormat2=new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
            String ymd = simpleDateFormat.format(nowDate);
            boolean condition1=false;
            boolean condition2=false;
            if(periodType.contains(CustomerCardSettingDetail.periodType_week)){
                Integer week=Integer.parseInt(CustomerCardSettingDetail.dateToWeek(nowDate));
                String weeklySelection = cardDetail.getWeeklySelection();
                List<Integer> weekList = Arrays.stream(weeklySelection.split(",")).map(s -> Integer.parseInt(s)).sorted(Comparator.comparingInt(i -> i)).collect(Collectors.toList());
                if(weekList.contains(week)){
                    condition1=true;
                }

                Integer startWeek = weekList.get(0);
                Integer endWeek = weekList.get(weekList.size() - 1);
                String ymdhms="";
                if(startWeek.equals(week)){
                    ymdhms=ymd+" "+cardDetail.getWeekEffectiveTimeStart().toString();
                    Date parse = simpleDateFormat2.parse(ymdhms);
                    if(nowDate.getTime()<parse.getTime()){
                        condition1=false;
                    }else{
                        condition1=true;
                    }
                }
                if(endWeek.equals(week)){
                    ymdhms=ymd+" "+cardDetail.getWeekEffectiveTimeEnd().toString();
                    Date parse = simpleDateFormat2.parse(ymdhms);
                    if(nowDate.getTime()>parse.getTime()){
                        condition1=condition1&&false;
                    }else{
                        condition1=condition1&&true;
                    }
                }
                if(startWeek.equals(endWeek)){
                    Date weekEffectiveTimeStart = simpleDateFormat2.parse(ymd + " " + cardDetail.getWeekEffectiveTimeStart().toString());
                    Date weekEffectiveTimeEnd = simpleDateFormat2.parse(ymd + " " + cardDetail.getWeekEffectiveTimeEnd().toString());
                    if(nowDate.getTime()<=weekEffectiveTimeEnd.getTime()&&nowDate.getTime()>=weekEffectiveTimeStart.getTime()){
                        condition1=true;
                    }else{
                        condition1=false;
                    }

                }
            }
            if(periodType.contains(CustomerCardSettingDetail.periodType_month)){
                Integer month=Integer.parseInt(CustomerCardSettingDetail.dateToMonth(nowDate));
                String monthlySelection = cardDetail.getMonthlySelection();
                List<Integer> monthList = Arrays.stream(monthlySelection.split(",")).map(s -> Integer.parseInt(s)).sorted(Comparator.comparingInt(i -> i)).collect(Collectors.toList());
                if(monthList.contains(month)){
                    condition2=true;
                }
                Integer startMonth = monthList.get(0);
                Integer endMonth = monthList.get(monthList.size() - 1);
                String ymdhms="";
                if(startMonth.equals(month)){
                    ymdhms = ymd+" "+cardDetail.getMonthEffectiveTimeStart().toString();
                    Date parse = simpleDateFormat2.parse(ymdhms);
                    if(nowDate.getTime()<parse.getTime()){
                        condition2=false;
                    }else{
                        condition2=true;
                    }
                }
                if(endMonth.equals(month)){
                    ymdhms = ymd+" "+cardDetail.getMonthEffectiveTimeEnd().toString();
                    Date parse = simpleDateFormat2.parse(ymdhms);
                    if(nowDate.getTime()>parse.getTime()){
                        condition2=condition2&&false;
                    }else{
                        condition2=condition2&&true;
                    }
                }
                if(endMonth.equals(startMonth)){
                    Date monthEffectiveTimeStart = simpleDateFormat2.parse(ymd + " " + cardDetail.getMonthEffectiveTimeStart().toString());
                    Date monthEffectiveTimeEnd = simpleDateFormat2.parse(ymd + " " + cardDetail.getMonthEffectiveTimeEnd().toString());
                    if(nowDate.getTime()<=monthEffectiveTimeEnd.getTime()&&nowDate.getTime()>=monthEffectiveTimeStart.getTime()){
                        condition1=true;
                    }else{
                        condition1=false;
                    }
                }
            }
            if(periodType.contains("all")){
                return true;
            }
            return condition1||condition2;
        }catch (Exception e){
            e.printStackTrace();
        }
        return false;
    }

    private Boolean timeInScope(LocalTime comparedTime ,LocalTime startTime, LocalTime endTime){
//        LocalTime nowTime = LocalTime.of(5,54,07);
        if(startTime == null || endTime == null){
            return true;  // 有一个为null 直接放行
        }else if(startTime.isBefore(endTime) && startTime.isBefore(comparedTime) && endTime.isAfter(comparedTime) ){
            return true;
            //  大 小
        }else if(startTime.isAfter(endTime) ){
            //小 大
            if(startTime.isBefore(comparedTime)){
                return true;
            }
            //大 小
            if(endTime.isAfter(comparedTime)){
                return true;
            }
        }else if(startTime.equals(comparedTime)){
            return true;
        }else if(endTime.equals(comparedTime)){
            return true;
        }
        return false;
    }
}
